import 'package:bike_ride/common/mvvm/base_page.dart';
import 'package:bike_ride/common/util/account_manager.dart';
import 'package:bike_ride/common/util/event_bus_utils.dart';
import 'package:bike_ride/common/util/extension.dart';
import 'package:bike_ride/common/util/hysize_fit.dart';
import 'package:bike_ride/common/widget/avatar.dart';
import 'package:bike_ride/common/widget/page_title_widget.dart';
import 'package:bike_ride/model/main/model/user_info_m.dart';
import 'package:bike_ride/model/mine/view_model/mine_vm.dart';
import 'package:bike_ride/generated/l10n.dart';
import 'package:bike_ride/res/style/color_styles.dart';
import 'package:bike_ride/res/style/text_styles.dart';
import 'package:bike_ride/res/style/theme_styles.dart';
import 'package:bike_ride/router/navigator_util.dart';
import 'package:bike_ride/router/routers.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

///个人中心
class MineView extends BaseStatefulPage<MineViewModel> {
  const MineView({super.key});

  @override
  MineViewState createState() => MineViewState();
}

class MineViewState extends BaseStatefulPageState<MineView, MineViewModel> {
  final topContainerHeight = 360.rpx;

  @override
  void initAttribute() {}

  @override
  void initObserver() {
    EventBusUtils.listen(UserInfoM(), (_) {
      viewModel?.getUserInfo();
      viewModel?.getFinanceInfo();
    });
  }

  @override
  MineViewModel viewBindingViewModel() {
    return MineViewModel()..viewState = this;
  }

  void notifyChange() {
    if (mounted) {
      setState(() {});
    }
  }

  @override
  Widget appBuild(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: true,
      backgroundColor: ColorStyles.color_F3F4F5,
      body: Builder(builder: (context) {
        final userInfo = AccountManager.userInfo;
        final isLogin = AccountManager.isLogin;

        return Stack(children: [
          Positioned(
            top: 0,
            left: 0,
            right: 0,
            child: Container(
              height: topContainerHeight + MediaQuery.of(context).padding.top,
              decoration: BoxDecoration(
                  gradient: LinearGradient(
                      begin: Alignment.topCenter,
                      end: Alignment.bottomCenter,
                      colors: [
                    Theme.of(context).colorScheme.primary,
                    ColorStyles.color_F3F4F5,
                  ])),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  PageTitleWidget(
                    title: S.current.personal,
                  ),
                  Container(
                    height: 88.rpx + 32.rpx,
                    margin: EdgeInsets.symmetric(
                        horizontal: ThemeStyles.pagePaddingHorizontal),
                    child: Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Avatar(
                              url: userInfo?.baseInfo?.avatar,
                              defaultPath: 'assets/images/default_face.png',
                              onTap: () {}),
                          SizedBox(width: 16.rpx),
                          Expanded(
                              child: Text(
                            (isLogin
                                ? userInfo?.baseInfo?.nickname ??
                                    S.current.defaultName
                                : S.current.clickToLogin),
                            style: TextStyles.style_page_title,
                          )),
                          if (isLogin)
                            TextButton(
                              onPressed: () {
                                NavigatorUtil.push(
                                    context, Routers.personalView,
                                    arguments: userInfo);
                              },
                              child: Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  Text(
                                    S.current.personInfo,
                                    style: TextStyle(
                                        color: const Color(0xFF848F99),
                                        fontSize: 32.rpx),
                                  ),
                                  Icon(
                                    Icons.arrow_forward_ios,
                                    size: 32.rpx,
                                    color: const Color(0xFF848F99),
                                  )
                                ],
                              ),
                            )
                        ]),
                  ),
                  if (isLogin)
                    SizedBox(
                      height: 88.rpx,
                      child: Row(children: [
                        Expanded(
                            child: flexText1SpreadItem(
                                key: S.current.amount,
                                value: viewModel!.balance,
                                onPress: () {
                                  NavigatorUtil.push(
                                      context, Routers.walletView);
                                })),
                        Expanded(
                            child: flexText1SpreadItem(
                                key: S.current.rideTicket,
                                value: viewModel!.countCards,
                                onPress: () {
                                  EasyLoading.showError(S.current.developerTips);
                                })),
                        Expanded(
                            child: flexText1SpreadItem(
                                key: S.current.discountCard,
                                value: viewModel!.countCoupons,
                                onPress: () {
                                  EasyLoading.showError(S.current.developerTips);
                                })),
                      ]),
                    ),
                ],
              ),
            ),
          ),

          /// 精选服务 +出行数据
          Positioned(
              top: (topContainerHeight + MediaQuery.of(context).padding.top) - 60.rpx - (isLogin ? 0 : 88.rpx),
              left: 0,
              right: 0,
              child: isLogin
                  ? Column(
                mainAxisSize: MainAxisSize.min,
                      children: [
                        Container(
                          padding: EdgeInsets.symmetric(
                              horizontal: 32.rpx, vertical: 24.rpx),
                          margin: EdgeInsets.symmetric(
                              horizontal: ThemeStyles.pagePaddingHorizontal,
                              vertical: 16.rpx),
                          decoration: ThemeStyles.defaultBoxDecoration,
                          child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  S.current.selectedService,
                                  style: TextStyle(
                                    fontSize: 28.rpx,
                                    color: ColorStyles.color_000000,
                                    fontWeight: FontWeight.bold,
                                    decoration: TextDecoration.underline,
                                    decorationColor: Theme.of(context)
                                        .colorScheme
                                        .primary
                                        .withOpacity(0.5),
                                    decorationStyle: TextDecorationStyle.solid,
                                  ),
                                ),
                                GridView(
                                  shrinkWrap: true,
                                  padding: EdgeInsets.only(top: 24.rpx),
                                  gridDelegate:
                                      SliverGridDelegateWithFixedCrossAxisCount(
                                    crossAxisSpacing: 32.rpx,
                                    crossAxisCount: 4,
                                  ),
                                  children: [
                                    flexBottomSpreadItem(
                                        key: S.current.mineTravelRecord,
                                        path: 'assets/images/icon-1.png',
                                        click: () {
                                          NavigatorUtil.push(context, Routers.cyclingRecordView);
                                        }),
                                    flexBottomSpreadItem(
                                        key: S.current.violationRecord,
                                        path: 'assets/images/icon-2.png',
                                        click: () {
                                          EasyLoading.showError(S.current.developerTips);
                                        }),
                                    flexBottomSpreadItem(
                                        key: S.current.discountMall,
                                        path: 'assets/images/icon-3.png',
                                        click: () {
                                          EasyLoading.showError(S.current.developerTips);
                                        }),
                                    flexBottomSpreadItem(
                                        key: S.current.freeDepCard,
                                        path: 'assets/images/icon-4.png',
                                        click: () {
                                          EasyLoading.showError(S.current.developerTips);
                                        }),
                                    flexBottomSpreadItem(
                                        key: S.current.exchangeCard,
                                        path: 'assets/images/icon-5.png',
                                        click: () {
                                          EasyLoading.showError(S.current.developerTips);
                                        }),
                                    flexBottomSpreadItem(
                                        key: S.current.feedback,
                                        path: 'assets/images/icon-6.png',
                                        click: () {
                                          NavigatorUtil.push(context, Routers.faultReportView);
                                        }),
                                    flexBottomSpreadItem(
                                        key: S.current.customerService,
                                        path: 'assets/images/icon-7.png',
                                        click: () {
                                          NavigatorUtil.push(context, Routers.questionView);
                                        }),
                                  ],
                                ),
                              ]),
                        ),
                        Container(
                            padding: EdgeInsets.symmetric(
                                horizontal: 32.rpx, vertical: 24.rpx),
                            margin: EdgeInsets.symmetric(
                                horizontal: ThemeStyles.pagePaddingHorizontal),
                            decoration: ThemeStyles.defaultBoxDecoration,
                            child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(S.current.travelData,
                                      style: TextStyle(
                                        fontSize: 28.rpx,
                                        color: ColorStyles.color_000000,
                                        fontWeight: FontWeight.bold,
                                        decoration: TextDecoration.underline,
                                        decorationColor: Theme.of(context)
                                            .colorScheme
                                            .primary
                                            .withOpacity(0.5),
                                        decorationStyle:
                                            TextDecorationStyle.solid,
                                      )),
                                  SizedBox(
                                    height: 24.rpx,
                                  ),
                                  Row(
                                    children: [
                                      flexText2SpreadItem(
                                        key: S.current.cyclingMileage,
                                        value: '0',
                                      ),
                                      SizedBox(width: 8.rpx,),
                                      flexText2SpreadItem(
                                        key: S.current.carbonEmission,
                                        value: '0',
                                      ),
                                      SizedBox(width: 8.rpx,),
                                      flexText2SpreadItem(
                                        key: S.current.cyclingDuration,
                                        value: '0',
                                      ),
                                      SizedBox(width: 8.rpx,),
                                      flexText2SpreadItem(
                                        key: S.current.plantTrees,
                                        value: '0',
                                      ),
                                    ],
                                  )
                                ]))
                      ],
                    )
                  : Container(
                      padding: EdgeInsets.symmetric(
                          horizontal: 32.rpx, vertical: 24.rpx),
                      margin: EdgeInsets.symmetric(
                          horizontal: 24.rpx, vertical: 16.rpx),
                      decoration: ThemeStyles.defaultBoxDecoration,
                      child: Column(children: [
                        protocolItem(S.current.chargeStandard, () {
                          NavigatorUtil.push(
                              context, Routers.freightView);
                        }),
                        protocolItem(S.current.privacyProtocol, () {
                          NavigatorUtil.push(context, Routers.webViewPage,
                              arguments: {
                                'url': AccountManager.privacyProtocolUrl,
                              });
                        }),
                      ]),
                    ))
        ]);
      }),
    );
  }

  Widget flexText1SpreadItem({required String key, Object? value,required Function() onPress}) {
    return GestureDetector(
      onTap: onPress,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Text(
            (value ?? '0').toString(),
            style: TextStyle(
                fontSize: 32.rpx,
                color: ColorStyles.color_1082FF,
                fontWeight: FontWeight.w500),
          ),
          Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text(
                key,
                style:
                TextStyle(fontSize: 24.rpx, color: ColorStyles.color_44515C),
              ),
              Icon(
                Icons.arrow_forward_ios,
                size: 28.rpx,
                color: const Color(0xFF848F99),
              )
            ],
          )
        ],
      ),
    );
  }

  Widget flexBottomSpreadItem(
      {required String key, required String path, required Function() click}) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: click,
      child: Column(
        children: [
          Padding(
            padding: const EdgeInsets.symmetric(vertical: 4),
            child: Image(
              width: 48.rpx,
              height: 48.rpx,
              image: AssetImage(path),
            ),
          ),
          Text(
            key.fixAutoLines(),
            style: TextStyles.style_000000_12,
            textAlign: TextAlign.center,
          )
        ],
      ),
    );
  }

  Widget flexText2SpreadItem({required String key, required String value}) {
    return Flexible(
      child: Column(
        children: [
          Text(
            value,
            style: TextStyle(
                fontSize: 32.rpx,
                color: ColorStyles.color_000000,
                fontWeight: FontWeight.w500),
          ),
          Text(
            key.fixAutoLines(),
            style: TextStyle(
                fontSize: 24.rpx,
                color: ColorStyles.color_000000.withOpacity(0.5)),
            textAlign: TextAlign.center,
          )
        ],
      ),
    );
  }

  Widget protocolItem(String title, Function() onclick) {
    return GestureDetector(
      onTap: onclick,
      child: SizedBox(
        height: 60.rpx,
        child: Row(
          children: [
            Icon(
              Icons.text_snippet_outlined,
              size: 28.rpx,
              color: ColorStyles.color_333333,
            ),
            SizedBox(
              width: 38.rpx,
            ),
            Expanded(
              child: Text(
                title,
                style: TextStyles.style_333333_13,
              ),
            ),
            Icon(
              Icons.arrow_forward_ios,
              size: 28.rpx,
              color: ColorStyles.color_999999,
            )
          ],
        ),
      ),
    );
  }
}
